<template>
  <div class="page-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          :inline="true"
          label-position="left"
          @submit.prevent
        >
          <el-form-item :label="$t('role.keyStr')">
            <el-input v-model="queryParams.roleKey" :placeholder="$t('role.keyTip')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item :label="$t('role.name')">
            <el-input v-model="queryParams.roleName" :placeholder="$t('role.nameTip')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item :label="$t('status')">
            <el-select v-model="queryParams.status" :placeholder="$t('select')" clearable @keyup.enter.native="handleQuery" style="width: 140px;">
              <el-option :label="$t('enabled')" value="1" />
              <el-option :label="$t('disabled')" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('createTime')" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              type="daterange"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{$t('query')}}</el-button>
            <el-button @click="reset">{{$t('reset')}}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div class="tool-controls">
      <el-button type="primary" plain :icon="Plus" @click="handleAdd">{{$t('add')}}</el-button>
    </div>

    <el-table v-loading="loading" :data="lists" :border="true">
      <el-table-column :label="$t('role.roleId')" align="center" prop="roleId" width="140" />
      <el-table-column :label="$t('role.keyStr')" align="center" prop="roleKey" width="140" />
      <el-table-column :label="$t('role.name')" align="center" prop="roleName" />
      <el-table-column :label="$t('role.description')" align="center" prop="remark" />
      <el-table-column :label="$t('status')" align="center" prop="status" width="100">
        <template #default="scope">
          <el-text v-if="scope.row.status == '1'" type="success">{{$t('enabled')}}</el-text>
          <el-text v-else type="danger">{{$t('disabled')}}</el-text>
        </template>
      </el-table-column>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="180" :formatter="formatterTime" />
      <el-table-column :label="$t('handle')" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button v-if="scope.row.roleId != 1" type="text" size="small" @click="handleEdit(scope.row)">{{$t('edit')}}</el-button>
          <el-button v-if="scope.row.roleId != 1" type="text" size="small" @click="handleDelete(scope.row)">{{$t('delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="lists.length > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="lists.length"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>

  <!--新增修改-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="460px">
    <el-form ref="userForm" :model="roleInfo" :rules="rules" label-width="auto">
      <el-form-item :label="$t('role.name')" prop="roleName">
        <el-input v-model="roleInfo.roleName" :placeholder="$t('role.nameTip')" />
      </el-form-item>
      <el-form-item :label="$t('role.keyStr')" prop="roleKey">
        <el-input v-model="roleInfo.roleKey" :placeholder="$t('role.keyTip')" />
      </el-form-item>
      <el-form-item :label="$t('status')" prop="status">
        <el-radio-group v-model="roleInfo.status">
          <el-radio label="1">{{$t('enabled')}}</el-radio>
          <el-radio label="0">{{$t('disabled')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('sort')" prop="roleSort">
        <el-input-number v-model="roleInfo.roleSort" :min="0" />
      </el-form-item>
      <el-form-item :label="$t('role.menuRole')" prop="menus">
        <div class="menu-role">
          <div class="btn">
            <el-checkbox
            v-model="checkExpand"
            @change="handleExpandChange"
            >展开/折叠</el-checkbox>
            <el-checkbox
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选/全不选</el-checkbox>
          </div>
          <div class="tree">
            <el-tree
              style="width: 100%;"
              ref="treeRef"
              :key="treeKey"
              :data="menuTreeData"
              show-checkbox
              check-strictly
              node-key="menuId"
              :default-checked-keys="roleInfo.menus"
              :props="{
                children: 'children',
                label: 'menuName',
              }"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('role.description')" prop="description">
        <el-input type="textarea" v-model="roleInfo.remark" :placeholder="$t('role.descriptionTip')" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{ $t('confirm') }}</el-button>
      <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from '#imports';
import { useI18n } from '#imports';
import type { FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import dayjs from 'dayjs';

const { t } = useI18n();

definePageMeta({
  title: '角色管理',
  en_title: 'Team Management',
})

interface QueryParams {
  roleKey: string;
  roleName: string;
  status: string;
  createTime: Array<string>;
}

interface RoleModel {
  roleId?: string;
  roleKey: string;
  roleName: string;
  remark: string;
  status: string;
  roleSort: number;
  menus?: number[];
}

const queryParams: Ref<QueryParams> = ref({
  roleKey: '',
  roleName: '',
  status: '',
  createTime: [],
})

const handleQuery = () => {
  currentPage.value = 1;
  getLists();
}

const reset = () => {
  queryParams.value = {
    roleKey: '',
    roleName: '',
    status: '1',
    createTime: [],
  }
}

const dialogVisible = ref(false);
const checkExpand = ref(false);
const checkAll = ref(false);
const treeRef = ref(null);
const treeKey = ref(Date.now());
const handleExpandChange = (val: any) => {
  const store = (treeRef as any).value.store;
  if (val) {
    const nodes = store._getAllNodes();
    nodes.forEach((item: any) => {
      item.expanded = true;
    });
  } else {
    const nodes = store._getAllNodes();
    nodes.forEach((item: any) => {
      item.expanded = false;
    });
  }
}

const handleCheckAllChange = (val: any) => {
  const instance = (treeRef as any).value;
  if (val) {
    const allKeys = getAllKeys(menuTreeData.value);
    instance.setCheckedKeys(allKeys);
  } else {
    instance.setCheckedKeys([]);
  }
}
// 获取所有节点的 key
const getAllKeys = (nodes: any) => {
  let keys: any = [];
  nodes.forEach((node: any) => {
    keys.push(node.menuId);
    if (node.children) {
      keys = keys.concat(getAllKeys(node.children));
    }
  });
  return keys;
};

const menuTreeData = ref([]);
const getMenuData = async () => {
  const result: any = await queryAllMenus();
  if (result?.code === 200) {
    menuTreeData.value = toTree(result.data, 'menuId', 'parentId');
  }
}
getMenuData();


const roleInfo: Ref<RoleModel> = ref({
  roleId: '',
  roleKey: '',
  roleName: '',
  remark: '',
  status: '1',
  roleSort: 0,
  menus: [],
});
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: t('role.nameTip'), trigger: 'blur' }],
  roleKey: [{ required: true, message: t('role.keyTip'), trigger: 'blur' }],
  status: [{ required: true, message: t('select'), trigger: 'change' }],
})
const dialogTitle = ref('');
const operateType = ref('');
const handleAdd = () => {
  dialogVisible.value = true;
  operateType.value = 'add';
  dialogTitle.value = t('add');
  treeKey.value = Date.now();
  roleInfo.value = {
    roleKey: '',
    roleName: '',
    remark: '',
    status: '1',
    roleSort: 0,
    menus: [],
  }
}

const handleEdit = (row: RoleModel) => {
  dialogVisible.value = true;
  operateType.value = 'edit';
  dialogTitle.value = t('edit');
  roleInfo.value = row;
  treeKey.value = Date.now();
}

const submitForm = async () => {
  const instance = (treeRef as any).value;
  roleInfo.value.menus = instance.getCheckedKeys();
  if (operateType.value === 'add') {
    const result: any = await roleCreate(roleInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('addSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  } else if (operateType.value === 'edit') {
    const result: any = await roleUpdate(roleInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('updateSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  }
  dialogVisible.value = false;
}

const handleDelete = (row: RoleModel) => {
  ElMessageBox.confirm(t('confirmDelete'), t('prompt'), {
    confirmButtonText: t('confirm'),
    cancelButtonText: t('cancel'),
    type: 'warning',
  }).then(async () => {
    const result: any = await roleDelete({ roleId: row.roleId });
    if (result?.code === 200) {
      ElMessage.success(t('deleteSuccess'));
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  })
}

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const lists: Ref = ref([]);
const getLists = async () => {
  loading.value = true;
  const params: {
    page: number;
    pageSize: number;
    roleKey?: string;
    roleName?: string;
    status?: string;
    startTime?: string;
    endTime?: string;
  } = {
    page: currentPage.value,
    pageSize: pageSize.value,
  }

  const { roleKey, roleName, status, createTime } = queryParams.value;
  roleKey && (params.roleKey = roleKey);
  roleName && (params.roleName = roleName);
  status && (params.status = status);
  if (createTime && createTime.length > 0) {
    params.startTime = dayjs(createTime[0]).format('YYYY-MM-DD');
    params.endTime = dayjs(createTime[1]).format('YYYY-MM-DD');
  }
  const result: any = await queryRoles(params);
  if (result?.code === 200) {
    lists.value = result.data.map((item: any) => {
      return {
        ...item,
        menus: item.menus.map((menu: any) => menu.menuId),
      }
    });
  }
  loading.value = false;
}
getLists();

const handleSizeChange = (val: number) => {
  currentPage.value = 1;
  pageSize.value = val;
  getLists();
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getLists();
}

const formatterTime = (data : any) => {
  return formatDate(data.createTime, 'YYYY-MM-DD HH:mm:ss');
}
</script>

<style lang="less">
.menu-role {
  width: calc(100% - 20px);
  .tree {
    margin-top: 4px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    width: 100%;
  }
}
</style>